package com.quanyan.search.service.impl;


import com.alibaba.dubbo.common.json.JSON;
import com.quanyan.api.APIResponse;
import com.quanyan.common.constants.SearchConstants;
import com.quanyan.common.utils.PinYinUtils;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.search.entity.request.ReqActivitySearchInfo;
import com.quanyan.search.entity.response.ActivitySearchResponse;
import com.quanyan.search.entity.response.SearchResponses;
import com.quanyan.search.entity.vo.ActivityIndexInfo;
import com.quanyan.search.service.ActivitySearchService;
import com.quanyan.search.utils.CommonUtil;
import com.quanyan.search.utils.SolrServerSingle;
import org.apache.commons.collections.CollectionUtils;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.impl.CloudSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.MapSolrParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.util.*;


/**
 * ActivitySearchServiceImpl
 * 搜索服务实现
 *
 * @author Tu Chun
 * @date 2016/6/3
 */
@Service("activitySearchService")
public class ActivitySearchServiceImpl implements ActivitySearchService {
    private static Logger logger = LoggerFactory.getLogger(ActivitySearchServiceImpl.class);
    //public final static String URL = "http://192.168.30.181:8080/solr";
    //public final static String URL = "192.168.30.181:2181,192.168.30.181:2182,192.168.30.181:2183";
    //public   static String URL = "192.168.30.75:2181,192.168.30.75:2182,192.168.30.75:2183";
    private String URL;

    public String getURL() {
        return URL;
    }

    public void setURL(String URL) {
        this.URL = URL;
    }


    public ActivitySearchServiceImpl(String url) {
        logger.warn("传入的solr地址为：" + url);
        this.URL = url;
    }

    public ActivitySearchServiceImpl() {
    }


    /**
     * 添加活动索引
     *
     * @param insertActivityIndexInfo
     * @return
     */
    @Override
    public APIResponse insertDoc(ActivityIndexInfo insertActivityIndexInfo) {
        try {
            logger.warn("solr地址：" + URL);
            if (addDocUtil(insertActivityIndexInfo)) {
                return APIResponse.returnSuccess("添加活动" + insertActivityIndexInfo.getActivity_name() + "索引c成功");
            } else {
                return APIResponse.returnFail("添加活动索引失败");
            }
        } catch (Exception e) {
            logger.error(e.getMessage() + "添加活动索引失败", e);
            return APIResponse.returnFail("添加活动索引失败");
        }
    }

    /**
     * 添加多个活动索引
     *
     * @param insertActivityIndexInfos
     * @return
     */
    @Override
    public APIResponse insertDocs(List<ActivityIndexInfo> insertActivityIndexInfos) {
        try {
            Long startTime = System.currentTimeMillis();
            Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            for (int i = 0; i < insertActivityIndexInfos.size(); i++) {
                ActivityIndexInfo indexInfo = insertActivityIndexInfos.get(i);
                //创建文档对象
                SolrInputDocument document = new SolrInputDocument();
                String uniqueId = SearchConstants.ACTIVITY_ID_PREFIX + UUID.randomUUID().toString();

                document.addField("id", uniqueId);
                document.addField("activity_id", indexInfo.getActivity_id());
                document.addField("activity_name_ik", indexInfo.getActivity_name());
                document.addField("activity_name", indexInfo.getActivity_name());
                document.addField("activity_name2", indexInfo.getActivity_name());
                document.addField("activity_categorieId", indexInfo.getActivity_categorieId());
                document.addField("activity_categorieName", indexInfo.getActivity_categorieName());
                document.addField("activity_cityId", indexInfo.getActivity_cityId());
                document.addField("activity_cityName", indexInfo.getActivity_cityName());
                document.addField("activity_districtId", indexInfo.getActivity_districtId());
                document.addField("activity_districtName", indexInfo.getActivity_districtName());
                document.addField("activity_latlng", indexInfo.getActivity_lat() + "," + indexInfo.getActivity_lng());
                document.addField("activity_site", indexInfo.getActivity_site());
                document.addField("activity_clubName", indexInfo.getActivity_clubName());
                document.addField("activity_price", indexInfo.getActivity_price());
                document.addField("activity_url", indexInfo.getActivity_url());
                document.addField("activity_startTime", CommonUtil.getSolrDate(CommonUtil.getDate(indexInfo.getActivity_startTime())));
                document.addField("activity_endTime", CommonUtil.getSolrDate(CommonUtil.getDate(indexInfo.getActivity_endTime())));
                document.addField("activity_isPrime", indexInfo.getActivity_isPrime());
                document.addField("activity_deadlineTime", indexInfo.getActivity_deadlineTime());
                document.addField("activity_isFull", indexInfo.getActivity_isFull());
                document.addField("activity_placeAddress", indexInfo.getActivity_placeAddress());
                document.addField("activity_name_pinyin", indexInfo.getActivity_name_pinyin());
                document.addField("activity_name_first_letter", indexInfo.getActivity_name_first_letter());
                document.addField("activity_clubName_pinyin", indexInfo.getActivity_clubName_pinyin());
                document.addField("activity_clubName_first_letter", indexInfo.getActivity_clubName_first_letter());
                document.addField("club_task", indexInfo.getClubTask());
                List<Integer> activity_dateParams = indexInfo.getActivity_dateParams();
                if (!CommonUtil.isNullOrZero(activity_dateParams)) {
                    for (int j = 0; j < activity_dateParams.size(); j++) {
                        document.addField("activity_dateParams", activity_dateParams.get(j));
                    }

                }
                docs.add(document);
                logger.warn("添加" + i + "号索引到文档中");
            }
            solrServer.add(docs);
            solrServer.commit();
            Long endTime = System.currentTimeMillis();
            logger.warn("添加索引" + insertActivityIndexInfos.size() + "条执行时间：" + ((endTime - startTime) / (60 * 1000)) + "分钟.");
            return APIResponse.returnSuccess("添加多个活动索引成功");
        } catch (Exception e) {
            logger.error(e.getMessage() + "添加多个活动索引异常", e);
            return APIResponse.returnFail("添加多个活动索引失败");
        }

    }

    /**
     * 删除多个Document
     *
     * @param ids
     * @return
     */
    @Override
    public APIResponse deleteDocsActivityByIds(List<Integer> ids) {

        try {
            if (CommonUtil.isNullOrZero(ids)) {
                return APIResponse.returnFail("俱乐部ids不能为空");
            }
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            solrServer.setDefaultCollection("collection2");

            StringBuilder stringBuilder = new StringBuilder();
//            stringBuilder.append("club_id:(");
//            for (int i = 0; i < ids.size(); i++) {
//                Integer id = ids.get(i);
//                if (i == 0) {
//                    stringBuilder.append(id);
//                } else {
//                    stringBuilder.append(" OR ").append(id);
//                }
//            }
//            stringBuilder.append(")");
            stringBuilder.append("activity_id:*");
            logger.warn("批量删除条件：" + stringBuilder.toString());
            solrServer.deleteByQuery(stringBuilder.toString());
            solrServer.commit();


            return APIResponse.returnSuccess("删除多个俱乐部活动索引成功");
        } catch (Exception e) {
            logger.error(e.getMessage() + "删除多个俱乐部活动索引异常", e);
            return APIResponse.returnFail("删除多个俱乐部活动引失败");
        }

    }

    /**
     * 根据id删除Document
     *
     * @param id
     * @return
     */
    @Override
    public APIResponse deleteDocById(Integer id) {
        try {
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            StringBuilder stringBuilder = new StringBuilder();
            if (CommonUtil.isNullOrZero(id)) {
                return APIResponse.returnFail("活动id不能为空");
            } else if (!CommonUtil.isNullOrZero(id)) {
                stringBuilder.append("activity_id:").append(id);
            }
            solrServer.deleteByQuery(stringBuilder.toString());
            solrServer.commit();
            return APIResponse.returnSuccess("删除活动索引成功");
        } catch (Exception e) {
            logger.error(e.getMessage() + "删除活动索引异常", e);
            return APIResponse.returnFail("删除活动索引失败");
        }
    }


    /**
     * 删除多个Document
     *
     * @param ids
     * @return
     */
    @Override
    public APIResponse deleteDocsByIds(List<Integer> ids) {
        //创建连接
        CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
        // 设置默认的collection
        solrServer.setDefaultCollection("collection2");
        try {
            if (CommonUtil.isNullOrZero(ids)) {
                return APIResponse.returnFail("活动ids不能为空");
            }
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("activity_id:(");
            for (int i = 0; i < ids.size(); i++) {
                Integer id = ids.get(i);
                if (i == 0) {
                    stringBuilder.append(id);
                } else {
                    stringBuilder.append(" OR ").append(id);
                }
            }
            stringBuilder.append(")");
            logger.warn("批量删除条件：" + stringBuilder.toString());
            solrServer.deleteByQuery(stringBuilder.toString());
            solrServer.commit();
            return APIResponse.returnSuccess("删除多个活动索引成功");

        } catch (Exception e) {
            logger.error(e.getMessage() + "删除多个活动索引异常", e);
            return APIResponse.returnFail("删除多个活动索引失败");
        }


    }


    /**
     * 根据id获取活动信息
     *
     * @param id
     * @return
     */
    @Override
    public APIResponse<ActivityIndexInfo> searchActivityInfo(Integer id) {
        try {
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            Map<String, String> params = new HashMap<String, String>();
            StringBuilder builder = new StringBuilder();
            if (CommonUtil.isNullOrZero(id)) {
                return APIResponse.returnFail("活动id不能为空");
            } else if (!CommonUtil.isNullOrZero(id)) {
                builder.append("activity_id:").append(id);
            }
            params.put("q", builder.toString());
            QueryResponse response = solrServer.query(new MapSolrParams(params), SolrRequest.METHOD.POST);
            SolrDocumentList solrDocumentList = response.getResults();
            List<ActivityIndexInfo> ActivityIndexInfoList = response.getBeans(ActivityIndexInfo.class);
            return APIResponse.returnSuccess(CommonUtil.isNullOrZero(ActivityIndexInfoList) ? null : ActivityIndexInfoList.get(0));
        } catch (Exception e) {
            logger.error(e.getMessage() + "根据id搜索活动异常", e);
            return APIResponse.returnFail("根据id搜索活动失败");
        }
    }

    /**
     * 根据条件搜索 新
     *
     * @param reqActivitySearchInfo
     * @return
     */
    @Override
    public APIResponse<SearchResponses<List<ActivitySearchResponse>>> searchActivityInfoListNew(ReqActivitySearchInfo reqActivitySearchInfo) {
        try {
            SearchResponses<List<ActivitySearchResponse>> searchResponses = new SearchResponses<List<ActivitySearchResponse>>();
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            Map<String, String> params = new HashMap<String, String>();
            Integer cityId = reqActivitySearchInfo.getCityId();
            Integer districtId = reqActivitySearchInfo.getDistrictId();
            Integer categoryId = reqActivitySearchInfo.getCategoryId();
            Integer sortType = reqActivitySearchInfo.getSortId();
            Integer dateParam = reqActivitySearchInfo.getDateParam();
            Double lat = reqActivitySearchInfo.getLat();
            Double lng = reqActivitySearchInfo.getLng();
            String name = reqActivitySearchInfo.getName();
            //1 按汉字搜 2 按英文搜 3 按首字母搜 4汉英混合搜 5按数字搜
            Byte searchType = reqActivitySearchInfo.getType();

            Integer pageNo = reqActivitySearchInfo.getPageNo();
            Integer pageSize = reqActivitySearchInfo.getPageSize();
            Integer startPosition = pageNo * pageSize;//首页为1
            StringBuilder builder = new StringBuilder();
            String currentSolrDate = CommonUtil.getSolrDate(CommonUtil.getDate(new Date()));

            List<Integer> categories = reqActivitySearchInfo.getCategories();
            //活动的结束时间大于当前时间
            builder.append("activity_endTime:").append(CommonUtil.getSolrDateScope3(currentSolrDate, "*"));
            logger.warn("name:" + name);
            if (!StringUtil.isBlankOrNull(name)) {

                if (searchType == 1) {
                    String namePingyin = PinYinUtils.hanyuToPinyin(name);
                    String nameFirstPingyin="";
                    if (namePingyin != null) {
                        namePingyin = namePingyin.replaceAll(":", "");
                        nameFirstPingyin = PinYinUtils.hanyuToPinyin(namePingyin.charAt(0) + "");
                    }

                    if (nameFirstPingyin != null) {
                        nameFirstPingyin = nameFirstPingyin.replaceAll(":", "");
                    }
                    //1 按汉字搜
                     builder.append(" AND (activity_name:").append(name + "^600");
                    builder.append(" OR activity_name:").append(name + "*^600");
                    builder.append(" OR activity_clubName:").append(name + "^200");
                    builder.append(" OR activity_clubName:").append(name + "*^200");
                    builder.append(")");
                } else if (searchType == 2) {
                    //2 按英文搜

                    builder.append(" AND (activity_name:").append(name + "^600");
                    builder.append(" OR activity_name:").append(name + "*^600");
                    builder.append(" OR activity_name_pinyin:").append("*" + name + "*" + "^600");
                    builder.append(" OR activity_name_first_letter:").append(name.charAt(0) + "");

                    builder.append(" OR activity_clubName:").append(name + "^200");
                    builder.append(" OR activity_clubName:").append(name + "*^200");
                    builder.append(" OR activity_clubName_pinyin:").append("*" + name + "*" + "^200");
                    builder.append(" OR activity_clubName_first_letter:").append(name.charAt(0) + "");

                    builder.append(")");

                } else if (searchType == 3) {
                    //3 按首字母搜
                    builder.append(" AND (activity_name:").append(name + "^600");
                    builder.append(" OR activity_name:").append(name + "*^600");
                    builder.append(" OR activity_name_first_letter:").append(name.charAt(0) + "^600");
                    builder.append(" OR activity_name_pinyin:").append("*" + name + "*");


                    builder.append(" OR activity_clubName:").append(name + "^200");
                    builder.append(" OR activity_clubName:").append(name + "*^200");
                    builder.append(" OR activity_clubName_first_letter:").append(name.charAt(0) + "^200");
                    builder.append(" OR activity_clubName_pinyin:").append("*" + name + "*");
                    builder.append(")");
                } else if (searchType == 4) {
                    //4汉英混合搜
                    builder.append(" AND (activity_name:").append(name + "^600");
                    builder.append(" OR activity_name:").append(name + "*^600");
                    builder.append(" OR activity_name_pinyin:").append("*" + name + "*^600");
                    builder.append(" OR activity_name_first_letter:").append(name.charAt(0) + "");


                    builder.append(" OR activity_clubName:").append(name + "^200");
                    builder.append(" OR activity_clubName:").append(name + "*^200");
                    builder.append(" OR activity_clubName_pinyin:").append("*" + name + "*^200");
                    builder.append(" OR activity_clubName_first_letter:").append(name.charAt(0) + "");

                    builder.append(")");
                } else if (searchType == 5) {
                    //5按数字搜
                    builder.append(" AND (activity_name:").append(name + "^600");
                    builder.append(" OR activity_name:").append(name + "*^600");
                    builder.append(" OR activity_name_first_letter:").append(name.charAt(0) + "*^600");
                    builder.append(" OR activity_name_pinyin:").append("*" + name + "*");


                    builder.append(" OR activity_clubName:").append(name + "^200");
                    builder.append(" OR activity_clubName:").append(name + "*^200");
                    builder.append(" OR activity_clubName_first_letter:").append(name.charAt(0) + "^200");
                    builder.append(" OR activity_clubName_pinyin:").append("*" + name + "*");
                    builder.append(")");
                }

                logger.warn("query:" + builder.toString());
                params.put("q", builder.toString());
                //params.put("fq", "{!geofilt}");//距离过滤函数
                params.put("pt", CommonUtil.getLatLng(lat, lng));//当前经纬度
                params.put("sfield", "activity_latlng");//经纬度的字段
                params.put("d", "20000" +
                        "");//就近20000公里的所有活动
                params.put("sort", "score desc,geodist() asc,activity_startTime asc");
            } else {
                if (!CommonUtil.isNullOrZero(cityId)) {
                    builder.append(" AND activity_cityId:").append(cityId);
                }
                if (!CommonUtil.isNullOrZero(districtId)) {
                    builder.append(" AND activity_districtId:").append(districtId);
                }
                if (!CommonUtil.isNullOrZero(categoryId)) {
                    builder.append(" AND activity_categorieId:").append(categoryId);
                } else if (CollectionUtils.isNotEmpty(categories)) {
                    builder.append("AND (");
                    int first = 0;
                    for (Integer category : categories) {
                        if (null != category && category.intValue() != 0) {
                            if (first == 1) {
                                builder.append(" OR ");
                            }
                            first = 1;
                            builder.append("activity_categorieId:")
                                    .append(category);
                        }
                    }
                    builder.append(")");
                }
                if (!CommonUtil.isNullOrZero(dateParam)) {
                    builder.append(" AND activity_dateParams:").append(dateParam);
                }
                logger.warn("query:" + builder.toString());
                params.put("q", builder.toString());
                params.put("fq", "{!geofilt}");//距离过滤函数
                params.put("pt", CommonUtil.getLatLng(lat, lng));//当前经纬度
                params.put("sfield", "activity_latlng");//经纬度的字段
                params.put("d", "20000");//就近20000公里的所有活动
                /**
                 * 排序id
                 * 1、智能排序（时间降序 距离升序）SearchConstants.ACTIVITY_SMART_SORT
                 * 2、离我最近 距离升序排序 SearchConstants.ACTIVITY_DISTANCE_SORT
                 * 3、时间升序排序  SearchConstants.ACTIVITY_TIME_SORT
                 */
                if (CommonUtil.isNullOrZero(sortType)) {
                    sortType = SearchConstants.ACTIVITY_SMART_SORT;
                }
                if (sortType == SearchConstants.ACTIVITY_DISTANCE_SORT) {
                    params.put("sort", "geodist() asc,activity_startTime asc,activity_price asc,score desc");//根据距离升序
                } else if (sortType == SearchConstants.ACTIVITY_TIME_SORT) {
                    params.put("sort", "activity_startTime asc,geodist() asc,activity_price asc,score desc");//时间升序排序
                } else if (sortType == SearchConstants.ACTIVITY_PRICE_SORT_ASC) {
                    params.put("sort", "activity_price asc,geodist() asc,activity_startTime asc");//价格升序排序
                } else if (sortType == SearchConstants.ACTIVITY_PRICE_SORT_DESC) {
                    params.put("sort", "activity_price desc,geodist() asc,activity_startTime asc");//价格降序排序
                } else if(sortType==SearchConstants.ACTIVITY_TASK_SORT_DESC){//俱乐部周任务排序,满足首页推荐要求
                    params.put("d", reqActivitySearchInfo.getDistance().toString());//就近distance的所有活动
                    params.put("sort","club_task desc,geodist() asc,activity_startTime asc,activity_price asc,score desc");
                }else {
                    /*//默认为智能排序
                    Integer activity_time = Integer.parseInt(Configure.getPropertyBykey("activity_time"));
                    //时间系数
                    double activity_time_modulus = Float.parseFloat(Configure.getPropertyBykey("activity_time_modulus")) * 1.0 / 3600000;
                    Float dist = Float.parseFloat(Configure.getPropertyBykey("activity_dist"));
                    //距离系数
                    Float activity_dist_modulus = Float.parseFloat(Configure.getPropertyBykey("activity_dist_modulus"));

                    params.put("defType", "edismax");
                    params.put("bf", "sum(recip(ms(activity_startTime," + currentSolrDate + ")," + activity_time_modulus + "," + activity_time + "," + 0.00 + "),recip(geodist()," + activity_dist_modulus + "," + dist + "," + 0.00 + "))");
                    //params.put("bf", "sum(recip(ms(" + currentSolrDate + ",activity_startTime),3.16e-11,1,1),recip(geodist()," + activity_dist_modulus + "," + dist + "," + dist + "))");
                    //params.put("bf", "ms(" + currentSolrDate + ",activity_startTime)");
                    params.put("sort", "score desc");//根据综合评分降序*/
                    //默认排序名称 距离 时间
                    params.put("sort", "geodist() asc,activity_startTime asc,activity_price asc,score desc");//根据综合评分降序*/
                }

            }
            params.put("fl", "*,activity_dist:geodist(),score");
            params.put("start", startPosition.toString());//记录开始位置
            params.put("rows", pageSize.toString());//查询的行数
            params.put("df", "activity_keywords");   // 设置默认搜索域
            //设置高亮
            /*params.put("hl", "true");
            params.put("hl.fl", "activity_name,activity_clubName");
            //params.put("hl.f2", "");
            params.put("hl.simple.pre", "<em style=\"color:red\">");
            params.put("hl.simple.post", "</em>");*/

            logger.warn("params:" + JSON.json(params));
            QueryResponse response = solrServer.query(new MapSolrParams(params), SolrRequest.METHOD.POST);
            SolrDocumentList solrDocumentList = response.getResults();
            long total = solrDocumentList.getNumFound();
            //取高亮显示
            /*Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();*/
            List<ActivityIndexInfo> activityIndexInfoList = response.getBeans(ActivityIndexInfo.class);
            List<ActivitySearchResponse> activityResList = getActivitySearchResponseListNew(solrDocumentList);
            searchResponses.setData(activityResList);
            searchResponses.setPageNo(pageNo);
            searchResponses.setPageSize(pageSize);
            searchResponses.setTotal((int) total);
            return APIResponse.returnSuccess(searchResponses);
        } catch (Exception e) {
            logger.error(e.getMessage() + "搜索数据异常", e);
            return APIResponse.returnFail("搜索数据异常");
        }
    }

    private List<ActivitySearchResponse> getActivitySearchResponseListNew(SolrDocumentList solrDocumentList) throws ParseException, IOException {
        List<ActivitySearchResponse> activityResList = new ArrayList<ActivitySearchResponse>();
        List<ActivityIndexInfo> activityIndexInfos = new ArrayList<ActivityIndexInfo>();
        for (SolrDocument solrDocument : solrDocumentList) {
            ActivityIndexInfo activityIndexInfo = new ActivityIndexInfo();
            //解析solr中数据
            String id = (String) solrDocument.get("id");
            String activityId = (String) solrDocument.get("activity_id");
            String activityName = (String) solrDocument.get("activity_name");
            Integer activityCategoryId = (Integer) solrDocument.get("activity_categorieId");
            String activityCategoryName = (String) solrDocument.get("activity_categorieName");
            Integer activityCityId = (Integer) solrDocument.get("activity_cityId");
            String activityCityName = (String) solrDocument.get("activity_cityName");
            Integer activityDistrictId = (Integer) solrDocument.get("activity_districtId");
            String activityDistrictName = (String) solrDocument.get("activity_districtName");
            String activityLatLng = (String) solrDocument.get("activity_latlng");
            Double activityLat = 0.0;
            Double activityLng = 0.0;
            if (!StringUtil.isBlankOrNull(activityLatLng)) {
                activityLat = Double.parseDouble(activityLatLng.split(",")[0]);
                activityLng = Double.parseDouble(activityLatLng.split(",")[1]);
            }
            String activitySite = (String) solrDocument.get("activity_site");
            String activityClubName = (String) solrDocument.get("activity_clubName");
            Double activityPrice = (Double) solrDocument.get("activity_price");
            String activityUrl = (String) solrDocument.get("activity_url");
            Date activityStartTime = (Date) solrDocument.get("activity_startTime");
            Date activityEndTime = (Date) solrDocument.get("activity_endTime");
            Integer activityIsPrime = (Integer) solrDocument.get("activity_isPrime");
            Date activityDeadlineTime = (Date) solrDocument.get("activity_deadlineTime");
            Integer activityIsFull = (Integer) solrDocument.get("activity_isFull");
            String placeAddress = (String) solrDocument.get("activity_placeAddress");
            List<Integer> activityDateParams = (List<Integer>) solrDocument.get("activity_dateParams");
            Float score = (Float) solrDocument.get("score");
            Float activityDist = (Float) solrDocument.get("activity_dist");
                Integer clubTask= (Integer) solrDocument.get("clubTask");
            activityStartTime = activityStartTime == null ? null : CommonUtil.getFormatDateByLong(activityStartTime.getTime());
            activityEndTime = activityEndTime == null ? null : CommonUtil.getFormatDateByLong(activityEndTime.getTime());
            activityDeadlineTime = activityDeadlineTime == null ? null : CommonUtil.getFormatDateByLong(activityDeadlineTime.getTime());
            activityDist = activityDist == null ? 0 : activityDist;
            activityDist = activityDist * 1000;

            //测试打印数据
            activityIndexInfo.setId(id);
            activityIndexInfo.setActivity_id(activityId);
            activityIndexInfo.setActivity_name(activityName);
            activityIndexInfo.setActivity_categorieId(activityCategoryId);
            activityIndexInfo.setActivity_categorieName(activityCategoryName);
            activityIndexInfo.setActivity_cityId(activityCityId);
            activityIndexInfo.setActivity_cityName(activityCityName);
            activityIndexInfo.setActivity_districtId(activityDistrictId);
            activityIndexInfo.setActivity_districtName(activityDistrictName);
            activityIndexInfo.setActivity_lat(activityLat);
            activityIndexInfo.setActivity_lng(activityLng);
            activityIndexInfo.setActivity_site(activitySite);
            activityIndexInfo.setActivity_clubName(activityClubName);
            activityIndexInfo.setActivity_price(activityPrice);
            activityIndexInfo.setActivity_url(activityUrl);
            activityIndexInfo.setActivity_startTime(activityStartTime);
            activityIndexInfo.setActivity_endTime(activityEndTime);
            activityIndexInfo.setActivity_isPrime(activityIsPrime);
            activityIndexInfo.setActivity_deadlineTime(activityDeadlineTime);
            activityIndexInfo.setActivity_isFull(activityIsFull);
            activityIndexInfo.setActivity_placeAddress(placeAddress);
            activityIndexInfo.setActivity_dateParams(activityDateParams);
            activityIndexInfo.setActivity_dist(activityDist);
            activityIndexInfo.setClubTask(clubTask);
            activityIndexInfos.add(activityIndexInfo);

            //封装返回的数据
            ActivitySearchResponse activityRes = new ActivitySearchResponse();

            activityRes.setActivityId(activityId);
            activityRes.setActivityName(activityName);
            activityRes.setActivityClubName(activityClubName);
            activityRes.setActivityPrice(activityPrice);
            activityRes.setActivitySite(activitySite);
            activityRes.setActivityUrl(activityUrl);
            activityRes.setActivityStartTime(activityStartTime);
            activityRes.setActivityEndTime(activityEndTime);
            activityRes.setActivityIsFull(activityIsFull);
            activityRes.setPlaceAddress(placeAddress);
            activityRes.setNowServerTime(new Date());

            activityRes.setActivityDist(activityDist);

            activityRes.setLat(activityLat);
            activityRes.setLng(activityLng);
            if (System.currentTimeMillis() - activityDeadlineTime.getTime() <= 0) {
                //验证score
                activityRes.setActivityIsDeadline(SearchConstants.ACTIVITY_NOT_DEADLINE);
            } else {
                activityRes.setActivityIsDeadline(SearchConstants.ACTIVITY_IS_DEADLINE);
            }
            activityRes.setClubTask(clubTask);
            activityResList.add(activityRes);
        }
        //测试打印数据
        logger.info("activityIndexInfos-size:" + activityIndexInfos.size());
        logger.info("activityIndexInfos:" + JSON.json(activityIndexInfos));

        return activityResList;

    }

    /**
     * 根据条件搜索
     *
     * @param reqActivitySearchInfo
     * @return
     */
    @Override
    public APIResponse<SearchResponses<List<ActivitySearchResponse>>> searchActivityInfoList(ReqActivitySearchInfo reqActivitySearchInfo) {
        try {
            SearchResponses<List<ActivitySearchResponse>> searchResponses = new SearchResponses<List<ActivitySearchResponse>>();
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            Map<String, String> params = new HashMap<String, String>();
            Integer cityId = reqActivitySearchInfo.getCityId();
            Integer districtId = reqActivitySearchInfo.getDistrictId();
            Integer categoryId = reqActivitySearchInfo.getCategoryId();
            Integer sortType = reqActivitySearchInfo.getSortId();
            Integer dateParam = reqActivitySearchInfo.getDateParam();
            Double lat = reqActivitySearchInfo.getLat();
            Double lng = reqActivitySearchInfo.getLng();
            String name = reqActivitySearchInfo.getName();

            Integer pageNo = reqActivitySearchInfo.getPageNo();
            Integer pageSize = reqActivitySearchInfo.getPageSize();
            Integer startPosition = pageNo * pageSize;//首页为1
            StringBuilder builder = new StringBuilder();
            String currentSolrDate = CommonUtil.getSolrDate(CommonUtil.getDate(new Date()));

            List<Integer> categories = reqActivitySearchInfo.getCategories();
            //活动的结束时间大于当前时间
            builder.append("activity_endTime:").append(CommonUtil.getSolrDateScope3(currentSolrDate, "*"));

            if (!StringUtil.isBlankOrNull(name)) {
                builder.append(" AND (activity_name:").append(name + "^2");
                builder.append(" OR activity_name:").append(name + "*^2");
                builder.append(" OR activity_clubName:").append(name + "^2");
                builder.append(" OR activity_clubName:").append(name + "*^2");
                builder.append(")");
                logger.warn("query:" + builder.toString());
                params.put("q", builder.toString());
                params.put("fq", "{!geofilt}");//距离过滤函数
                params.put("pt", CommonUtil.getLatLng(lat, lng));//当前经纬度
                params.put("sfield", "activity_latlng");//经纬度的字段
                params.put("d", "20000");//就近20000公里的所有活动
                params.put("sort", "score desc,geodist() asc,activity_startTime asc");
            } else {
                if (!CommonUtil.isNullOrZero(cityId)) {
                    builder.append(" AND activity_cityId:").append(cityId);
                }
                if (!CommonUtil.isNullOrZero(districtId)) {
                    builder.append(" AND activity_districtId:").append(districtId);
                }
                if (!CommonUtil.isNullOrZero(categoryId)) {
                    builder.append(" AND activity_categorieId:").append(categoryId);
                } else if (CollectionUtils.isNotEmpty(categories)) {
                    builder.append("AND (");
                    int first = 0;
                    for (Integer category : categories) {
                        if (null != category && category.intValue() != 0) {
                            if (first == 1) {
                                builder.append(" OR ");
                            }
                            first = 1;
                            builder.append("activity_categorieId:")
                                    .append(category);
                        }
                    }
                    builder.append(")");
                }
                if (!CommonUtil.isNullOrZero(dateParam)) {
                    builder.append(" AND activity_dateParams:").append(dateParam);
                }
                logger.warn("query:" + builder.toString());
                params.put("q", builder.toString());
                params.put("fq", "{!geofilt}");//距离过滤函数
                params.put("pt", CommonUtil.getLatLng(lat, lng));//当前经纬度
                params.put("sfield", "activity_latlng");//经纬度的字段
                params.put("d", "20000");//就近20000公里的所有活动
                /**
                 * 排序id
                 * 1、智能排序（时间降序 距离升序）SearchConstants.ACTIVITY_SMART_SORT
                 * 2、离我最近 距离升序排序 SearchConstants.ACTIVITY_DISTANCE_SORT
                 * 3、时间升序排序  SearchConstants.ACTIVITY_TIME_SORT
                 */
                if (CommonUtil.isNullOrZero(sortType)) {
                    sortType = SearchConstants.ACTIVITY_SMART_SORT;
                }
                if (sortType == SearchConstants.ACTIVITY_DISTANCE_SORT) {
                    params.put("sort", "geodist() asc,activity_startTime asc,score desc");//根据距离升序
                } else if (sortType == SearchConstants.ACTIVITY_TIME_SORT) {
                    params.put("sort", "activity_startTime asc,geodist() asc,score desc");//时间升序排序
                } else if (sortType == SearchConstants.ACTIVITY_PRICE_SORT_ASC) {
                    params.put("sort", "activity_price asc,geodist() asc,activity_startTime asc");//价格升序排序
                } else if (sortType == SearchConstants.ACTIVITY_PRICE_SORT_DESC) {
                    params.put("sort", "activity_price desc,geodist() asc,activity_startTime asc");//价格降序排序
                } else {
                    /*//默认为智能排序
                    Integer activity_time = Integer.parseInt(Configure.getPropertyBykey("activity_time"));
                    //时间系数
                    double activity_time_modulus = Float.parseFloat(Configure.getPropertyBykey("activity_time_modulus")) * 1.0 / 3600000;
                    Float dist = Float.parseFloat(Configure.getPropertyBykey("activity_dist"));
                    //距离系数
                    Float activity_dist_modulus = Float.parseFloat(Configure.getPropertyBykey("activity_dist_modulus"));

                    params.put("defType", "edismax");
                    params.put("bf", "sum(recip(ms(activity_startTime," + currentSolrDate + ")," + activity_time_modulus + "," + activity_time + "," + 0.00 + "),recip(geodist()," + activity_dist_modulus + "," + dist + "," + 0.00 + "))");
                    //params.put("bf", "sum(recip(ms(" + currentSolrDate + ",activity_startTime),3.16e-11,1,1),recip(geodist()," + activity_dist_modulus + "," + dist + "," + dist + "))");
                    //params.put("bf", "ms(" + currentSolrDate + ",activity_startTime)");
                    params.put("sort", "score desc");//根据综合评分降序*/
                    //默认排序名称 距离 时间
                    params.put("sort", "geodist() asc,activity_startTime asc,score desc");//根据综合评分降序*/
                }

            }
            params.put("fl", "*,activity_dist:geodist(),score");
            params.put("start", startPosition.toString());//记录开始位置
            params.put("rows", pageSize.toString());//查询的行数
            params.put("df", "activity_keywords");   // 设置默认搜索域
            //设置高亮
            /*params.put("hl", "true");
            params.put("hl.fl", "activity_name,activity_clubName");
            //params.put("hl.f2", "");
            params.put("hl.simple.pre", "<em style=\"color:red\">");
            params.put("hl.simple.post", "</em>");*/

            logger.warn("params:" + JSON.json(params));
            QueryResponse response = solrServer.query(new MapSolrParams(params), SolrRequest.METHOD.POST);
            SolrDocumentList solrDocumentList = response.getResults();
            long total = solrDocumentList.getNumFound();
            //取高亮显示
            /*Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();*/
            List<ActivityIndexInfo> activityIndexInfoList = response.getBeans(ActivityIndexInfo.class);
            List<ActivitySearchResponse> activityResList = getActivitySearchResponseList(solrDocumentList);
            searchResponses.setData(activityResList);
            searchResponses.setPageNo(pageNo);
            searchResponses.setPageSize(pageSize);
            searchResponses.setTotal((int) total);
            return APIResponse.returnSuccess(searchResponses);
        } catch (Exception e) {
            logger.error(e.getMessage() + "搜索数据异常", e);
            return APIResponse.returnFail("搜索数据异常");
        }
    }

    private List<ActivitySearchResponse> getActivitySearchResponseList(SolrDocumentList solrDocumentList) throws ParseException, IOException {
        List<ActivitySearchResponse> activityResList = new ArrayList<ActivitySearchResponse>();
        List<ActivityIndexInfo> activityIndexInfos = new ArrayList<ActivityIndexInfo>();
        for (SolrDocument solrDocument : solrDocumentList) {
            ActivityIndexInfo activityIndexInfo = new ActivityIndexInfo();
            //解析solr中数据
            String id = (String) solrDocument.get("id");
            String activityId = (String) solrDocument.get("activity_id");
            String activityName = (String) solrDocument.get("activity_name");
            Integer activityCategoryId = (Integer) solrDocument.get("activity_categorieId");
            String activityCategoryName = (String) solrDocument.get("activity_categorieName");
            Integer activityCityId = (Integer) solrDocument.get("activity_cityId");
            String activityCityName = (String) solrDocument.get("activity_cityName");
            Integer activityDistrictId = (Integer) solrDocument.get("activity_districtId");
            String activityDistrictName = (String) solrDocument.get("activity_districtName");
            String activityLatLng = (String) solrDocument.get("activity_latlng");
            Double activityLat = 0.0;
            Double activityLng = 0.0;
            if (!StringUtil.isBlankOrNull(activityLatLng)) {
                activityLat = Double.parseDouble(activityLatLng.split(",")[0]);
                activityLng = Double.parseDouble(activityLatLng.split(",")[1]);
            }
            String activitySite = (String) solrDocument.get("activity_site");
            String activityClubName = (String) solrDocument.get("activity_clubName");
            Double activityPrice = (Double) solrDocument.get("activity_price");
            String activityUrl = (String) solrDocument.get("activity_url");
            Date activityStartTime = (Date) solrDocument.get("activity_startTime");
            Date activityEndTime = (Date) solrDocument.get("activity_endTime");
            Integer activityIsPrime = (Integer) solrDocument.get("activity_isPrime");
            Date activityDeadlineTime = (Date) solrDocument.get("activity_deadlineTime");
            Integer activityIsFull = (Integer) solrDocument.get("activity_isFull");
            String placeAddress = (String) solrDocument.get("activity_placeAddress");
            List<Integer> activityDateParams = (List<Integer>) solrDocument.get("activity_dateParams");
            Float score = (Float) solrDocument.get("score");
            Float activityDist = (Float) solrDocument.get("activity_dist");

            /*Map<String, List<String>> stringListMap = highlighting.get(solrDocument.get("id").toString());
            List<String> activityNameList = null;
            List<String> activityClubNameList= null;*/
            //取高亮显示的结果
            /*if (stringListMap != null && stringListMap.size() > 0) {
                activityNameList = stringListMap.get("activity_name");
                activityClubNameList = stringListMap.get("activity_clubName");
            }
            if (activityNameList != null && activityNameList.size() > 0 ) {
                activityName = activityNameList.get(0);
            }if(activityClubNameList != null && activityClubNameList.size() > 0 ){
                activityClubName = activityClubNameList.get(0);
            }else {
                activityName = (String) solrDocument.get("activity_name");
                activityClubName=(String) solrDocument.get("activity_clubName");
            }*/
            activityStartTime = activityStartTime == null ? null : CommonUtil.getFormatDateByLong(activityStartTime.getTime());
            activityEndTime = activityEndTime == null ? null : CommonUtil.getFormatDateByLong(activityEndTime.getTime());
            activityDeadlineTime = activityDeadlineTime == null ? null : CommonUtil.getFormatDateByLong(activityDeadlineTime.getTime());
            activityDist = activityDist == null ? 0 : activityDist;
            activityDist = activityDist * 1000;
            //logger.info("solr得分score>>>>>>>>>>>>>：" + score);
            //logger.warn("开始时间>>>>>>>>>>>>>："+CommonUtil.getDate(activityStartTime));
            //params.put("bf", "sum(recip(ms(" + currentSolrDate + ",activity_startTime)," + activity_time_modulus + "," + activity_time + "," + activity_time + "),recip(geodist()," + activity_dist_modulus + "," + dist + "," + dist + "))");
            //logger.info("开始时间：" + CommonUtil.getDate(activityStartTime) + "  截止时间：" + CommonUtil.getDate(activityDeadlineTime));
            double jsCore = 16 * 1.0 / (0.00 + 1.0 * 1.0 / 3600000 * Math.abs(new Date().getTime() - activityStartTime.getTime())) + 8 * 1.0 / (0.00 + 1.00 * activityDist);
            //logger.info("计算得分score>>>>>>>>>>>>>：" + String.format("16*1.0/(0.00+(1.0*%d)/3600000)+8*1.0/(0.00+1.0*%f)=%f", Math.abs(new Date().getTime() - activityStartTime.getTime()), activityDist, jsCore));


            //测试打印数据
            activityIndexInfo.setId(id);
            activityIndexInfo.setActivity_id(activityId);
            activityIndexInfo.setActivity_name(activityName);
            activityIndexInfo.setActivity_categorieId(activityCategoryId);
            activityIndexInfo.setActivity_categorieName(activityCategoryName);
            activityIndexInfo.setActivity_cityId(activityCityId);
            activityIndexInfo.setActivity_cityName(activityCityName);
            activityIndexInfo.setActivity_districtId(activityDistrictId);
            activityIndexInfo.setActivity_districtName(activityDistrictName);
            activityIndexInfo.setActivity_lat(activityLat);
            activityIndexInfo.setActivity_lng(activityLng);
            activityIndexInfo.setActivity_site(activitySite);
            activityIndexInfo.setActivity_clubName(activityClubName);
            activityIndexInfo.setActivity_price(activityPrice);
            activityIndexInfo.setActivity_url(activityUrl);
            activityIndexInfo.setActivity_startTime(activityStartTime);
            activityIndexInfo.setActivity_endTime(activityEndTime);
            activityIndexInfo.setActivity_isPrime(activityIsPrime);
            activityIndexInfo.setActivity_deadlineTime(activityDeadlineTime);
            activityIndexInfo.setActivity_isFull(activityIsFull);
            activityIndexInfo.setActivity_placeAddress(placeAddress);
            activityIndexInfo.setActivity_dateParams(activityDateParams);
            activityIndexInfo.setActivity_dist(activityDist);
            activityIndexInfos.add(activityIndexInfo);

            //封装返回的数据
            ActivitySearchResponse activityRes = new ActivitySearchResponse();

            activityRes.setActivityId(activityId);
            activityRes.setActivityName(activityName);
            activityRes.setActivityClubName(activityClubName);
            activityRes.setActivityPrice(activityPrice);
            activityRes.setActivitySite(activitySite);
            activityRes.setActivityUrl(activityUrl);
            activityRes.setActivityStartTime(activityStartTime);
            activityRes.setActivityEndTime(activityEndTime);
            activityRes.setActivityIsFull(activityIsFull);
            activityRes.setPlaceAddress(placeAddress);
            activityRes.setNowServerTime(new Date());

            activityRes.setActivityDist(activityDist);

            activityRes.setLat(activityLat);
            activityRes.setLng(activityLng);
            if (System.currentTimeMillis() - activityDeadlineTime.getTime() <= 0) {
                //验证score
                activityRes.setActivityIsDeadline(SearchConstants.ACTIVITY_NOT_DEADLINE);
            } else {
                activityRes.setActivityIsDeadline(SearchConstants.ACTIVITY_IS_DEADLINE);
            }

            activityResList.add(activityRes);
        }
        //测试打印数据
        logger.info("activityIndexInfos-size:" + activityIndexInfos.size());
        logger.info("activityIndexInfos:" + JSON.json(activityIndexInfos));

        return activityResList;

    }


    private boolean addDocUtil(ActivityIndexInfo indexInfo) {
        try {
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            //创建文档对象
            SolrInputDocument document = new SolrInputDocument();
            String uniqueId = SearchConstants.ACTIVITY_ID_PREFIX + UUID.randomUUID().toString();

            document.addField("id", uniqueId);
            document.addField("activity_id", indexInfo.getActivity_id());
            document.addField("activity_name_ik", indexInfo.getActivity_name());
            document.addField("activity_name", indexInfo.getActivity_name());
            document.addField("activity_name2", indexInfo.getActivity_name());
            document.addField("activity_categorieId", indexInfo.getActivity_categorieId());
            document.addField("activity_categorieName", indexInfo.getActivity_categorieName());
            document.addField("activity_cityId", indexInfo.getActivity_cityId());
            document.addField("activity_cityName", indexInfo.getActivity_cityName());
            document.addField("activity_districtId", indexInfo.getActivity_districtId());
            document.addField("activity_districtName", indexInfo.getActivity_districtName());
            document.addField("activity_latlng", indexInfo.getActivity_lat() + "," + indexInfo.getActivity_lng());
            document.addField("activity_site", indexInfo.getActivity_site());
            document.addField("activity_clubName", indexInfo.getActivity_clubName());
            document.addField("activity_price", indexInfo.getActivity_price());
            document.addField("activity_url", indexInfo.getActivity_url());
            document.addField("activity_startTime", CommonUtil.getSolrDate(CommonUtil.getDate(indexInfo.getActivity_startTime())));
            document.addField("activity_endTime", CommonUtil.getSolrDate(CommonUtil.getDate(indexInfo.getActivity_endTime())));
            document.addField("activity_isPrime", indexInfo.getActivity_isPrime());
            document.addField("activity_deadlineTime", CommonUtil.getSolrDate(CommonUtil.getDate(indexInfo.getActivity_deadlineTime())));
            document.addField("activity_isFull", indexInfo.getActivity_isFull());
            document.addField("activity_placeAddress", indexInfo.getActivity_placeAddress());
            document.addField("activity_name_pinyin", indexInfo.getActivity_name_pinyin());
            document.addField("activity_name_first_letter", indexInfo.getActivity_name_first_letter());
            document.addField("activity_clubName_pinyin", indexInfo.getActivity_clubName_pinyin());
            document.addField("activity_clubName_first_letter", indexInfo.getActivity_clubName_first_letter());
            document.addField("club_task",indexInfo.getClubTask());
            List<Integer> activity_dateParams = indexInfo.getActivity_dateParams();
            if (!CommonUtil.isNullOrZero(activity_dateParams)) {
                for (int i = 0; i < activity_dateParams.size(); i++) {
                    document.addField("activity_dateParams", activity_dateParams.get(i));
                }

            }
            solrServer.add(document);
            solrServer.commit();
            logger.warn("添加活动索引成功");
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage() + "添加活动索引失败", e);
            return false;
        }
    }
}
